package com.bw.house.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.house.common.ResponseResult;
import com.bw.house.entity.TbHouse;
import com.bw.house.mapper.TbHouseMapper;
import com.bw.house.service.ITbHouseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 邢晋宁
 * @since 2020-09-04
 */
@Service
public class TbHouseServiceImpl extends ServiceImpl<TbHouseMapper, TbHouse> implements ITbHouseService {

    @Autowired
    private TbHouseMapper houseMapper;

    @Autowired
    private ITbHouseService houseService;

    @Value("${filePath}")
    private String filePath;

    @Value("${housePath}")
    private String housePath;

    /**
     * 房东房源列表
     **/
    @Override
    public ResponseResult listAll(int currentPage, int pageSize, TbHouse house) {

        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(currentPage,pageSize);
            QueryWrapper queryWrapper = new QueryWrapper();
            List<TbHouse> houseList = new ArrayList<>();
            if(house.getName()!=null){//房屋名称
                queryWrapper.like("NAME","%"+house.getName()+"%");
            }
            if(house.getName()!=null){//房屋地址
                queryWrapper.like("ADDR","%"+house.getAddr()+"%");
            }
            if(house.getOwner()!=null){//房屋所属人员
                queryWrapper.eq("OWNER",house.getOwner());
            }
            if(house.getStatus()!=null){//房屋状态
                queryWrapper.eq("STATUS",house.getStatus());
            }
            if(house.getAddr()!=null){//房屋地址
                queryWrapper.like("ADDR","%"+house.getAddr()+"%");
            }
            if(house.getOwner()==null){//中介登录

                houseList = houseMapper.selectList(queryWrapper);
            }else{//房东登录
                queryWrapper.eq("STATUS",0);//房东只能查看自己的列表
                houseList = houseMapper.selectList(queryWrapper);
            }

            PageInfo pageInfo = new PageInfo(houseList);

            result.setResult(pageInfo);
            result.setMessage("查询成功！！！");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败！！！"+e.toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 房东房源添加
     **/
    @Override
    public ResponseResult addHouse(TbHouse house) {

        ResponseResult result = ResponseResult.SUCCESS();
        try {
            house.setNum(1);
            houseService.saveOrUpdate(house);
            result.setMessage("添加成功！！！");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("添加失败！！！"+e.toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 房东修改房源
     **/
    @Override
    public ResponseResult updateHouse(TbHouse house) {

        ResponseResult result = ResponseResult.SUCCESS();
        try {

            houseMapper.updateById(house);
            result.setMessage("修改成功！！！");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("修改失败！！！"+e.toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 房东删除房源
     **/
    @Override
    public ResponseResult deleteHouse(long id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            houseMapper.deleteById(id);
            result.setMessage("删除成功！！！");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("删除失败！！！"+e.toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 房东查询房源信息
     **/
    @Override
    public ResponseResult getByHoueseId(long id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbHouse tbHouse = houseMapper.selectById(id);
            result.setResult(tbHouse);
            result.setMessage("删除成功！！！");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("删除失败！！！"+e.toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 审核通过
     **/
    @Override
    public ResponseResult updateStatus(long id, TbHouse house) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbHouse tbHouse = houseMapper.selectById(id);
            tbHouse.setStatus(house.getStatus());
            houseMapper.updateById(tbHouse);

            if(tbHouse.getStatus()==1){//审核通过生成静态页面
                this.getHtml(tbHouse);
            }else{
                //删除静态页面
                File file=new File(housePath+tbHouse.getId()+".html");
                file.delete();
            }

            result.setMessage("审核通过！！！");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("审核未通过！！！"+e.toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 中介修改定价
     **/
    @Override
    public ResponseResult saveHouse(TbHouse house) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbHouse tbHouse = houseMapper.selectById(house.getId());
            tbHouse.setDprice(house.getDprice());
            houseMapper.updateById(tbHouse);
            result.setMessage("定价成功！！！");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("定价失败！！！"+e.toString());
            e.printStackTrace();
        }
        return result;
    }


    //生成一个课程静态页面
    public void getHtml(TbHouse house){

        try {
            Configuration configuration=new Configuration(Configuration.getVersion());//创建模板引擎配置
            ClassPathResource classPathResource=new ClassPathResource("template");
            //加载模板的路径【文件目录或者文件夹】
            configuration.setDirectoryForTemplateLoading(classPathResource.getFile());
            configuration.setDefaultEncoding("utf-8");//设置编码格式
            Template template= configuration.getTemplate("house-item.html");

            Map map=new HashMap();
            map.put("house", JSON.toJSONString(house));
            //模板+数据合成的具体的页面
            String htmlStr= FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
            InputStream inputStream= IOUtils.toInputStream(htmlStr,"utf-8");//将字符串转换成输入流
            FileOutputStream outputStream=new FileOutputStream(housePath+house.getId()+".html");
            IOUtils.copy(inputStream,outputStream);
            outputStream.close();
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
